package com.example.security.handler;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author 朽
 */
@Component
@NoArgsConstructor
@AllArgsConstructor
public class SecurityAuthenticationAccessHandler implements AuthorizationManager<RequestAuthorizationContext> {
    @Resource
    private AntPathMatcher antPathMatcher;

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication,RequestAuthorizationContext context) {

        HttpServletRequest request = context.getRequest();
        return new AuthorizationDecision(authentication
                .get()
                .getAuthorities()
                .stream()
                .anyMatch((Predicate<GrantedAuthority>) grantedAuthority ->
                        antPathMatcher.match(grantedAuthority.getAuthority(), request.getRequestURI())));
    }

    @Override
    public void verify(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        System.out.println("SecurityAuthenticationAccessHandler verify 执行了");
    }

}
